<?php

namespace BoxShadow\UsersBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use BoxShadow\UsersBundle\Entity\Users;
use BoxShadow\UsersBundle\Form\Model\Registration;

class AccountController extends Controller
{
    public function registerAction()
    {
        $form = $this->createForm('registration', new Registration());

        return $this->render('BoxShadowUsersBundle:Account:register.html.twig', array('form' => $form->createView()));
    }
    
    public function createAction()
    {
        $account = new Users();
        $registration = new Registration();
        
        $form = $this->createForm('registration',$registration);
        $form->handleRequest($this->getRequest());

        if ($form->isValid()) {
            
            /**
            $role_id = $this
                    ->getDoctrine()
                    ->getEntityManager()
                    ->getRepository('BoxShadowUsersBundle:Role')
                    ->find(1);
            $registration->getUsers()->setRoles($id_role);
            **/
            
            $factory = $this->get('security.encoder_factory');
            $encoder = $factory->getEncoder($account);
            $password = $encoder->encodePassword($registration->getUsers()->getPassword(), $registration->getUsers()->getSalt());
            $registration->getUsers()->setPassword($password);

            $em = $this->getDoctrine()->getEntityManager();

            $id_role = $em->getRepository('BoxShadowUsersBundle:Role')->findRoleId();
            $registration->getUsers()->setRoles($id_role);

            $em->persist($registration->getUsers());
            $em->flush();

            return $this->redirect($this->generateUrl('box_shadow_users_homepage'));
        }

        return $this->render('BoxShadowUsersBundle:Account:register.html.twig', array('form' => $form->createView()));
    }
}
